var Consts = require('../../../util/consts');
var KillerRole = Consts.KillerRole;
var killerRoomDao = require('../../../dao/killer/killerRoomDao');
var killerUserDao = require('../../../dao/killer/killerUserDao');

module.exports = function (app) {
    return new KillerRoomHandler(app);
};


var KillerRoomHandler = function (app) {
    this.app = app;
};
var handler = KillerRoomHandler.prototype;


// TODO: Argar platform migration -- using new chat room!
handler.createRoom = function (msg, session, next) {

    var rid = msg.rid;
    var usernames = msg.usernames || "[]";
    var master = msg.master;

    var self = this;
    killerRoomDao.getRoom(rid, function (err, room) {
        if (room && room.id) {
            next(null, {code: 400, msg: 'room already exists'});
            return;
        }
        var userList = JSON.parse(usernames);
        killerRoomDao.createRoom(master, rid, userList, function (err, room) {
            if (room) {
                var users = JSON.parse(usernames);
                var userCount = users.length;
                var killerCount = Math.floor(userCount / 3);


                users.sort(function (a, b) {
                    return Math.random() > .5 ? -1 : 1;
                });

                for (var i = 0; i < users.length; i++) {
                    var username = users[i];
                    var role = KillerRole.COMMONER;
                    if (i < killerCount) {
                        role = KillerRole.KILLER;
                    }
                    var seq = i + 1;
                    killerUserDao.createUser(username, rid, false, true, role, Consts.KillerPhase.INIT, seq, function (err, user) {
                        if (err) {
                            console.error('create user failed: ' + err);
                        }
                    });
                }
                next(null, {code: 200});
            } else {
                next(null, {code: 400});
            }
        });
    });


};